import argparse
import csv

def parse_input(input_lines):
    nodes = []
    current_indent = -1
    current_node = None
    
    for line in input_lines:
        line = line.rstrip()
        if not line:
            continue
            
        # 计算缩进级别
        indent = 0
        while line.startswith('    '):
            indent += 1
            line = line[4:]
            
        # 分离注释和内容
        if '｜' in line:
            content, comment = line.split('｜', 1)
            content = content.strip()
            comment = comment.strip()
        else:
            content = line.strip()
            comment = ''
            
        # 节点处理
        if content:
            # 新节点
            current_node = {
                'indent': indent,
                'name': content,
                'comment': comment,
                'full_path': []
            }
            nodes.append(current_node)
            current_indent = indent
        elif comment and current_node and indent == current_indent:
            # 追加注释到当前节点，用分号分隔
            if current_node['comment']:
                current_node['comment'] += ';' + comment
            else:
                current_node['comment'] = comment
                
    return nodes

def build_hierarchy(nodes):
    stack = []
    for node in nodes:
        # 弹出栈中缩进级别大于等于当前节点的元素
        while stack and stack[-1]['indent'] >= node['indent']:
            stack.pop()
            
        # 构建完整路径
        if stack:
            parent_path = stack[-1]['full_path']
            node['full_path'] = parent_path + [node['name']]
        else:
            node['full_path'] = [node['name']]
            
        stack.append(node)
        
    return nodes

def convert_to_csv(nodes):
    csv_data = []
    for idx, node in enumerate(nodes, start=1):
        tag = '.'.join(node['full_path'])
        csv_data.append({
            'Name': str(idx),
            'Tag': tag,
            'DevComment': node['comment']
        })
    return csv_data

def main():
    parser = argparse.ArgumentParser(description='Convert structured text to UE GameplayTag CSV format')
    parser.add_argument('-i', '--input', required=True, help='Input file path')
    parser.add_argument('-o', '--output', required=True, help='Output CSV file path')
    args = parser.parse_args()
    
    # 读取输入文件
    with open(args.input, 'r', encoding='utf-8') as f:
        input_lines = f.readlines()
    
    # 解析处理
    nodes = parse_input(input_lines)
    nodes = build_hierarchy(nodes)
    csv_data = convert_to_csv(nodes)
    
    # 写入CSV
    with open(args.output, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=['Name', 'Tag', 'DevComment'])
        writer.writeheader()
        writer.writerows(csv_data)

if __name__ == '__main__':
    main()